/**
 * Copyright (C) 2011 KingCore Science & Technology CO,.LTD. All rights reserved.
 * XNS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/**
 * Copyright (C) 2002-2011 WUZEWEN. All rights reserved.
 * WUZEWEN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * This software is the confidential and proprietary information of
 * WuZeven, Personal. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with WuZeven.
 */

package wzw.beans;

import java.util.Comparator;

import org.apache.log4j.Logger;

import wzw.util.ComponentUtil;

/**
 * <p>java class file describe</p>
 * @author Zeven on 2011-3-11
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @since	JDK5
 */

public class TolerantNumberComparator implements Comparator<Object> {

	/**
	 * <p>java method describe</p>
	 * @author Zeven on 2011-3-11
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	//log object
	private final static Logger log = Logger.getLogger(TolerantNumberComparator.class);
	
	private Class clazz = null;
	public TolerantNumberComparator(Class clazz) {
		super();
		this.clazz = clazz;
	}

	public static boolean isNullNumber(Object obj){
		return obj==null || obj.toString().trim().equals("");
	}
	public int compare(Object obj1, Object obj2) { 
		//log.info((obj1==null?"null":obj1.toString()) + " -- "+ (obj2==null?"null":obj2.toString()) );
		if ( isNullNumber(obj1) ) {
			if ( isNullNumber(obj2) ) {
				return 0;
			}else{
				return -1;
			}
		}else if( isNullNumber(obj2) ){
			return 1;
		}

		java.lang.Float int1, int2;
		String tmp_str = null;
		try {
			int1 = Float.parseFloat(obj1.toString());   //Float is better than Long.
		} catch (Exception e) {
			tmp_str = ComponentUtil.filterUnNumber(obj1.toString());
			if (tmp_str==null || tmp_str.trim().equals("")) {
				int1 = null;
			}else{
//				System.out.println("tmp_str="+tmp_str);
				int1 = Float.parseFloat( tmp_str );
			}
		}
		try {
			int2 = Float.parseFloat(obj2.toString());
		} catch (Exception e) {
			tmp_str = ComponentUtil.filterUnNumber(obj2.toString());
			if (tmp_str==null || tmp_str.trim().equals("")) {
				int2 = null;
			}else{
				int2 = Float.parseFloat( tmp_str );
			}
		}
		//log.info((obj1==null?"null":obj1.toString()) + " -- "+ (obj2==null?"null":obj2.toString()) );
		
		if ( isNullNumber(int1) ) {
			if ( isNullNumber(int2) ) {
				return 0;
			}else{
				return -1;
			}
		}else if( isNullNumber(int2) ){
			return 1;
		}
		
		return (int) (int1-int2);
    }
}
